import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/entity/task_entity.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/modle/person/bloc/my_money_bloc.dart';
import 'package:shopping_group/modle/person/ui/change_money_view_page.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/play/bloc/xianjingjuan_play_bloc.dart';
import 'package:shopping_group/modle/play/entity/user_account_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';
import 'package:bot_toast/bot_toast.dart';

class YongjinOnlyPalyPage extends StatefulWidget {
  final CommoSpec4AppRecordEntity entity;
  YongjinOnlyPalyPage({Key key, this.entity}) : super(key: key);

  @override
  _YongjinOnlyPalyPageState createState() => _YongjinOnlyPalyPageState();
}

class _YongjinOnlyPalyPageState extends State<YongjinOnlyPalyPage> {
//时间格式
  String _content = '00:59:59';
  XianJianJuanPlayBloc _bloc;
  MyMoneyBloc _myMoneyBloc;
  List<TaskEntity> _selectList = [];
  UserAccountEntity _moneyEntity = UserAccountEntity();
  StreamSubscription _validateSubscription;
  StreamSubscription _completeSubscription;
  @override
  void initState() {
    super.initState();
    _bloc = XianJianJuanPlayBloc();
    _bloc.timerDate.add(_content);
    _myMoneyBloc = MyMoneyBloc();
    _myMoneyBloc.initDate.add(null);

    _selectList
      ..add(TaskEntity()
        ..id = '1'
        ..title = '推广费余额 ¥${BaseConstant.integralAccount}'
        ..url = 'http://static.jiujiupingou.com/Static/img/bg21.png'
        ..isCilke = true);

    _validateSubscription = eventBus.on<ValidateYjEvent>().listen((event) {
      Map<String, dynamic> data = {};
      data['userId'] = BaseConstant.userId;
      data['moneyQuanSpecId'] = this.widget.entity.id;
      data['payUuid'] = this.widget.entity.payUuid;
      data['payOption'] = BaseConstant.PO_YON_JIN;
      data['payVal'] = this.widget.entity.realCharge;
      data['byYonJin'] = 'Y';
      data['moId'] = event.lastJoinId;
      _bloc.playCompetDate.add(data);
    });

    _completeSubscription = eventBus.on<YjCompeteEvent>().listen((event) {
      RouteUtil.popUntil(PageConstance.MAIN_PAGE);
      RouteUtil.goParameter(ChangeViewMoneyPage());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '去支付'),
      body: Container(
        height: double.infinity,
        decoration: new BoxDecoration(
          color: Colours.gray_f0,
        ),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  _timeView(),
                  SizedBox(
                    height: 32,
                  ),
                  _moneyView(),
                  SizedBox(
                    height: 8,
                  ),
                  _selectView(),
                ],
              ),
            ),
            ButtonProgressView.crateCupertinoView('确认支付',
                blackColor: Colours.main_01, cupertinoCall: () {
              _selectList.forEach((element) {
                bool notye = double.parse(
                        ObjectUtil.isEmptyString(this.widget.entity.realCharge)
                            ? '0'
                            : this.widget.entity.realCharge) >
                    double.parse(BaseConstant.integralAccount);
                if (element.isCilke && '1' == element.id && notye) {
                  BotToast.showText(text: '支付余额不足');
                  return;
                } else if (element.isCilke) {
                  _zfBloc(element);
                  return;
                }
              });
            }),
            SizedBox(
              height: 32,
            ),
          ],
        ),
      ),
    );
  }

  _zfBloc(element) {
    Map<String, dynamic> data = {};
    data['userId'] = BaseConstant.userId;
    data['moneyQuanSpecId'] = this.widget.entity.id;
    data['payUuid'] = this.widget.entity.payUuid;
    data['payOption'] = BaseConstant.PO_YON_JIN;
    data['payVal'] = this.widget.entity.realCharge;
    data['byYonJin'] = 'Y';
    _bloc.validateDate.add(data);
  }

  Widget _selectView() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      child: Column(
        children: <Widget>[
          WidgetUtils.getTextColorView(
              '选择支付方式', Colours.text_2222, Dimens.FONT_SIZE_18),
          SizedBox(
            height: 16,
          ),
          _selectFsView(),
        ],
      ),
    );
  }

  Widget _selectFsView() {
    return StreamBuilder(
      stream: _myMoneyBloc.sendAllData,
      initialData: _moneyEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is UserAccountEntity) {
          _moneyEntity = object;
        }
        // if (null != this.widget.entity && 'N' == this.widget.entity.isReBuy) {
        //   _selectList[1].title = '可用余额 ¥${_entity.allAccount}';
        // }
        return Column(
          children: _selectList.map((TaskEntity entity) {
            bool isEnd = _selectList[_selectList.length - 1].id == entity.id;
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectList.forEach((element) {
                    element.isCilke = false;
                  });
                  entity.isCilke = true;
                });
              },
              child: Container(
                color: Colours.transparent,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                            child: Row(
                          children: <Widget>[
                            WidgetUtils.buildNetworkImageView(entity.url,
                                width: 24, height: 24),
                            SizedBox(
                              width: 8,
                            ),
                            WidgetUtils.getTextColorView(entity.title,
                                Colours.text_2222, Dimens.FONT_SIZE_16),
                          ],
                        )),
                        Icon(
                          entity.isCilke
                              ? Icons.radio_button_checked
                              : Icons.radio_button_unchecked,
                          color: entity.isCilke
                              ? Colours.themeColor
                              : Colours.gray_f0,
                          size: 24,
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    isEnd ? Container() : WidgetUtils.drawCodeDivider(),
                    isEnd
                        ? Container()
                        : SizedBox(
                            height: 12,
                          ),
                  ],
                ),
              ),
            ); //赋值后的Widget
          }).toList(),
        );
      },
    );
  }

  Widget _moneyView() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      child: WidgetUtils.getTextColorView('¥ ${this.widget.entity.realCharge}',
          Colours.text_2222, Dimens.FONT_SIZE_30),
    );
  }

  Widget _timeView() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      alignment: Alignment.center,
      color: Colours.blackground_black_239,
      child: StreamBuilder(
        stream: _bloc.sendDate,
        initialData: _content,
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.data is String) {
            _content = snapshot.data;
          }
          return WidgetUtils.getTextColorView(
              '剩余时间$_content', Colours.yanqi_red, Dimens.FONT_SIZE_20);
        },
      ),
    );
  }

  @override
  void deactivate() {
    _bloc?.dispose();
    _validateSubscription?.cancel();
    _completeSubscription?.cancel();
    super.deactivate();
  }
}
